import os
import serial
from struct import *
import time

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow
from test_gui import Ui_MainWindow

app = QApplication(sys.argv)
wnd = QMainWindow()
uiDesign = Ui_MainWindow()
uiDesign.setupUi(wnd)
uiDesign.pushButton.clicked.connect(lambda: DoWork())

from serial.tools.list_ports import comports
for port in comports():
    uiDesign.cmbPorts.addItem(port.name)
    # print("port.name: ",port.name)

file_path = "../data_plugin/pstats/pstats.dat"
with open(file = file_path, mode = 'rb') as f:
    data = f.read()
block_num = int(os.path.getsize(file_path)/512/8)
# print(block_num) == 446
lead_name = ['I', 'II', 'V1', 'V2', 'V3', 'V4', 'V5', 'V6']
output = {}
for name in lead_name:
    output[name] = []
index = 0    #从data[40960]开始，因为前边一段时间的心电记录可能会不稳定或噪音比较多
for k in range(block_num):   # 读取数据块数，这里时间原因只读取10块
    for i in range(8):   # 导联数
        for j in range(256):  #每一导联的数据点数
            byte_low = bin(data[index])   #这里读取两个字节
            byte_high = bin(data[index+1])
            index+=2    #每读取两个字节，对data的索引加2
            data_plot = str(byte_high[3:]+byte_low[2:])   #两个字节以二进制拼接，并且要祛除符号位
            if byte_high[2] == '0':   # 符号位为正，直接按照原码读取
                value = int(data_plot, 2) * 0.0122    #二进制转化为十进制，并且按照规则将单位转化为mv
            elif byte_high[2] == '1':  #符号位为负，按照补码的规则转化为原码
                negative = ''    
                for m in range(len(data_plot)):  #对除符号位以外的取反
                    if data_plot[m] == '0':
                        negative += '1'
                    elif data_plot[m] == '1':
                        negative += '0'
                    else:
                        print("data_plot is not 0 or 1!")
                value = -1 * (int(negative, 2)+1) * 0.0122    
            else:
                print("data符号出错！")
                # print(value)
            output[lead_name[i]].append(value)
print(output["II"][10000])
print(len(output["II"]))

'''
# 8通道换算12通道计算公式
III = II - I
aVR = -(I+II)/2
aVL =  I - II/2
aVF = II - I/2
'''
for name_add in ['III', 'aVR', 'aVL', 'aVF']:
     output[name_add] = []
for i in range(len(output['I'])):
    output['III'].append(output['II'][i] - output['I'][i])
    output['aVR'].append(output['II'][i] - output['I'][i] * 0.5)
    output['aVL'].append(output['I'][i] - output['II'][i] * 0.5)
    output['aVF'].append((output['II'][i] + output['I'][i]) * 0.5)

def DoWork():
    uiDesign.pushButton.setText('测试中')
    uiDesign.pushButton.setEnabled(False)
    QApplication.processEvents()
    serName = uiDesign.cmbPorts.currentText()
    ser = serial.Serial(serName) # 改为你虚拟出来的一对串口中的其中一个
    # 扫描可用串口
    lists = ['I', 'II', 'V1', 'V2', 'V3', 'V4', 'V5', 'V6', 'III', 'aVR', 'aVL', 'aVF']
    y1=[]
    y2=[]
    y3=[]
    y4=[]
    y5=[]
    y6=[]
    y7=[]
    y8=[]
    y9=[]
    y10=[]
    y11=[]
    y12=[]

    for j in range(len(output["I"])):
        y1.append(output[lists[0]][j])
        # print(y1[j])
        y2.append(output[lists[1]][j])
        y3.append(output[lists[2]][j])
        y4.append(output[lists[3]][j])
        y5.append(output[lists[4]][j])
        y6.append(output[lists[5]][j])
        y7.append(output[lists[6]][j])
        y8.append(output[lists[7]][j])
        y9.append(output[lists[8]][j])
        y10.append(output[lists[9]][j])
        y11.append(output[lists[10]][j])
        y12.append(output[lists[11]][j])
        '''for i in range(len(y1)):
        y1 = float(y1[i])
        y2 = float(y2[i])
        y3 = float(y3[i])
        y4 = float(y4[i])
        y5 = float(y5[i])
        y6 = float(y6[i])
        y7 = float(y7[i])
        y8 = float(y8[i])
        y9 = float(y9[i])
        y10 = float(y10[i])
        y11 = float(y11[i])
        y12 = float(y12[i])
        '''
        dat = pack('ffffffffffffBBBB', y1[j], y2[j], y3[j], y4[j], y5[j], y6[j], y7[j], 
                    y8[j], y9[j], y10[j], y11[j], y12[j], 0x00, 0x00, 0x80, 0x7F)
        ser.write(dat)
        # break
        time.sleep(0.1)
    ser.close()
    uiDesign.pushButton.setText('测试')
    uiDesign.pushButton.setEnabled(True)

wnd.show()
app.exec_()
